package com.example.textview;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.FileProvider;

import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.hardware.usb.UsbManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.ParcelFileDescriptor;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;

import com.example.textview.usbrecive.USBReceiver;
import com.example.textview.usbrecive.UsbCallBack;
import com.example.textview.util.CopyFile;
import com.example.textview.util.GetPathFromUri;
import com.example.textview.util.ToastUtil;

import java.io.File;
import java.io.FileDescriptor;
import java.io.FileOutputStream;
import java.io.IOException;

public class ImageSelcetActivity extends AppCompatActivity {


    private static int RESULT_LOAD_IMAGE = 10;

    private static final int IMAGE = 1;

    private IntentFilter intentFilter;
    private USBReceiver usbReceiver;
    private String usbRootPath="";
    ImageView imageView;

    String Tag="ImageSelcetActivity";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_image_selcet);

        creatDic();


        intentFilter = new IntentFilter();
        intentFilter.addAction("android.intent.action.BOOT_COMPLETED");
        intentFilter.addAction("android.intent.action.MEDIA_REMOVED");
        intentFilter.addAction("android.intent.action.MEDIA_MOUNTED");

        intentFilter.addAction(UsbManager.ACTION_USB_ACCESSORY_ATTACHED);
        intentFilter.addAction(UsbManager.ACTION_USB_ACCESSORY_DETACHED);
        intentFilter.addAction(UsbManager.ACTION_USB_DEVICE_ATTACHED);
        intentFilter.addAction(UsbManager.ACTION_USB_DEVICE_DETACHED);

        usbReceiver = new USBReceiver();
        usbReceiver.usbCallBack=new UsbCallBack() {
            @Override
            public void usbDiskPath(String path) {
                ToastUtil.showMsg(ImageSelcetActivity.this,path);
                usbRootPath=path+"/";
                Log.e("eee",path);
            }
        };

        registerReceiver(usbReceiver, intentFilter);


        Button buttonLoadImage = findViewById(R.id.buttonLoadPicture);
        buttonLoadImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                //点击事件，而重定向到图片库
//                Intent intent = new Intent(
//                        Intent.ACTION_PICK,
//                        android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
//                //这里要传一个整形的常量RESULT_LOAD_IMAGE到startActivityForResult()方法。
//                startActivityForResult(intent, RESULT_LOAD_IMAGE);

              //  "/mnt/usb_storage/USB_DISK2/"
               // open(usbRootPath);
                open();

                //  openAssignFolder("mnt/usb_storage/USB_DISK2/");


                //  openU(v);

            }
        });

        imageView = findViewById(R.id.picture);
        String strFile=Environment.getExternalStorageDirectory().getAbsolutePath() + "/picture/123.jpg";
        if(fileIsExists(Environment.getExternalStorageDirectory().getAbsolutePath() + "/picture/123.jpg")) {

            Bitmap bmp = BitmapFactory.decodeFile(strFile);
            imageView.setImageBitmap(bmp);
            ToastUtil.showMsg(getApplicationContext(),"文件存在");
        }
        else {

            ToastUtil.showMsg(getApplicationContext(),"文件bu存在");
        }

    }


    //判断文件是否存在
    public boolean fileIsExists(String strFile)
    {
        try
        {
            File f=new File(strFile);
            if(!f.exists())
            {
                return false;
            }

        }
        catch (Exception e)
        {
            return false;
        }

        return true;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(usbReceiver);
    }

    private void open() {

try {
    //  File destDir = new File(getApplicationContext().getExternalCacheDir() + "//eml");

    File destDir = new File(getApplicationContext().getExternalCacheDir() + "/");

    Uri contentUri = FileProvider.getUriForFile(getApplicationContext(), "com.rfid.application.MyApplication.provider", destDir);

    Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
   // intent.setDataAndType(Uri.fromFile(destDir), "*/*");
    intent.setDataAndType(contentUri, "*/*");
    intent.addCategory(Intent.CATEGORY_OPENABLE);
    startActivityForResult(intent, RESULT_LOAD_IMAGE);
}
catch ( Exception EX)
{

    Log.d("abc",EX.getMessage());
    ToastUtil.showMsg(ImageSelcetActivity.this,EX.getMessage());
}




    }

    private void open(String path) {

        ToastUtil.showMsg(ImageSelcetActivity.this, path);
        File destDir = new File(path);


        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        intent.setDataAndType(Uri.fromFile(destDir), "*/*");
        intent.addCategory(Intent.CATEGORY_OPENABLE);
        startActivityForResult(intent, RESULT_LOAD_IMAGE);


//        if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
//
//            return;
//        }
//        //获取文件下载路径
//        String compName = AppString.getCompanyName();
//        String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/" + compName + "/OSC_DATA/";
//        File dir = new File(path);
//        if (!dir.exists()) {
//            dir.mkdirs();
//        }
//        //调用系统文件管理器打开指定路径目录
//        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
//        intent.setDataAndType(Uri.fromFile(dir.getParentFile()), "file/*.txt");
//        intent.addCategory(Intent.CATEGORY_OPENABLE);
//        startActivityForResult(intent, REQUEST_CHOOSEFILE);
    }


    private void openU(View view) {
        Intent intent;

        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) {
            intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);

        } else {
            intent = new Intent(Intent.ACTION_GET_CONTENT);

        }

        intent.setType("*/*");

        intent.addCategory(Intent.CATEGORY_OPENABLE);

        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

        this.startActivityForResult(intent, view.getId());
    }


    private void openAssignFolder(String path) {
        File file = new File(path);
        ToastUtil.showMsg(ImageSelcetActivity.this, path);
        if (null == file || !file.exists()) {
            ToastUtil.showMsg(ImageSelcetActivity.this, "找不到文件");
            return;
        }
        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        intent.addCategory(Intent.CATEGORY_DEFAULT);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setDataAndType(Uri.fromFile(file), "file/*");
        try {
            //  startActivity(intent);
//            startActivity(Intent.createChooser(intent,"选择浏览工具"));

            startActivityForResult(intent, RESULT_LOAD_IMAGE);
        } catch (ActivityNotFoundException e) {
            e.printStackTrace();
        }
    }

    //  用户选择一张图片，onActivityResult()方法将会被调用，
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);


//我们需要判断requestCode是否是我们之前传给startActivityForResult()方法的RESULT_LOAD_IMAGE，并且返回的数据不能为空


        if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) {


            Uri selectedImage = data.getData();

            // ToastUtil.showMsg(ImageSelcetActivity.this,selectedImage.toString());

            String[] filePathColumn = {MediaStore.Images.Media.DATA};
            //查询我们需要的数据
            Cursor cursor = getContentResolver().query(selectedImage,
                    filePathColumn, null, null, null);
            cursor.moveToFirst();

            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
            String picturePath = cursor.getString(columnIndex);

            // showImage(picturePath);

            ToastUtil.showMsg(ImageSelcetActivity.this, picturePath);
            cursor.close();


            //imageView.setImageBitmap(BitmapFactory.decodeFile(picturePath));

            //  Glide.with(this).load(picturePath).into(imageView);
            Bitmap bmp = null;
            try {

                bmp = getBitmapFromUri(selectedImage);

               savepicture(bmp);

               Log.d(Tag,"uri:"+selectedImage);
              String path=  GetPathFromUri.getPathFromUri(getApplicationContext(),selectedImage);
                Log.d(Tag,"路径为："+path);
            String name=  CopyFile.getFileName(path);
                Log.d(Tag,"文件名为："+name);



                String dir = Environment.getExternalStorageDirectory().getAbsolutePath() + "/picture/";

                CopyFile.copyFile(path,dir+name);

                ToastUtil.showMsg(getApplicationContext(),"文件保存成功");

            } catch (IOException e) {

                // TODO Auto-generated catch block

                e.printStackTrace();

            }

            imageView.setImageBitmap(bmp);

        }

    }


    private Bitmap getBitmapFromUri(Uri uri) throws IOException {

        ParcelFileDescriptor parcelFileDescriptor =

                getContentResolver().openFileDescriptor(uri, "r");

        FileDescriptor fileDescriptor = parcelFileDescriptor.getFileDescriptor();

        Bitmap image = BitmapFactory.decodeFileDescriptor(fileDescriptor);

        parcelFileDescriptor.close();

        return image;

    }


//    @Override
//    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
//        super.onActivityResult(requestCode, resultCode, data);
//        //获取图片路径
//        if (requestCode == IMAGE && resultCode == Activity.RESULT_OK && data != null) {
//            Uri selectedImage = data.getData();
//            String[] filePathColumns = {MediaStore.Images.Media.DATA};
//            Cursor c = getContentResolver().query(selectedImage, filePathColumns, null, null, null);
//            c.moveToFirst();
//            int columnIndex = c.getColumnIndex(filePathColumns[0]);
//            String imagePath = c.getString(columnIndex);
//            showImage(imagePath,data);
//            c.close();
//
//            ToastUtil.showMsg(ImageSelcetActivity.this,imagePath);
//        }
//    }


    //加载图片
    private void showImage(String imaePath, Intent data) {


        Bitmap bm = data.getExtras().getParcelable("data");
        ((ImageView) findViewById(R.id.picture)).setImageBitmap(bm);
    }


    //加载图片
    private void showImage(String imaePath) {
        Bitmap bm = BitmapFactory.decodeFile(imaePath);
        ((ImageView) findViewById(R.id.picture)).setImageBitmap(bm);
    }



    private void creatDic(){
        String dir = Environment.getExternalStorageDirectory().getAbsolutePath() + "/picture/";
        File dirFirstFolder = new File(dir);//方法二：通过变量文件来获取需要创建的文件夹名字
        if(!dirFirstFolder.exists())
        { //如果该文件夹不存在，则进行创建
            dirFirstFolder.mkdirs();//创建文件夹

        }

    }


    private void savepicture(Bitmap image)
    { String dir = Environment.getExternalStorageDirectory().getAbsolutePath() + "/picture/";

        try {
            File file = new File(dir + 123 + ".jpg");
            FileOutputStream out = new FileOutputStream(file);
            image.compress(Bitmap.CompressFormat.JPEG, 100, out);
            out.flush();
            out.close();
            //保存图片后发送广播通知更新数据库
            Uri uri = Uri.fromFile(file);
            sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, uri));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


}